import IntegrationTable, {
	IntegrationTableProps,
} from "@/components/IntegrationTable";
import { ProColumns } from "@ant-design/pro-table";
import React, { useEffect, useState } from "react";
import { Image, Radio, Cascader } from "antd";
import { areaList, classifyList, classify } from "./service";
import { getArray, arrayToObject } from "phinney-toolkit";
import { DynamicFormItem } from "@/components/DynamicForm";

// @page 商家
const Business: React.FC<any> = () => {
	// 组件是否已经卸载
	let isUnMounted = false;
	const conditionList = [
		{ label: "全新", value: "全新" },
		{ label: "九成新", value: "九成新" },
		{ label: "八成新", value: "八成新" },
		{ label: "七成新", value: "七成新" },
		{ label: "轻微使用痕迹", value: "轻微使用痕迹" },
	];

	const recommendList = [
		{ label: "是", value: 1 },
		{ label: "否", value: 0 },
	];

	const statusList = [
		{ label: "启用", value: 1 },
		{ label: "禁用", value: 0 },
	];
	let [area, setArea] = useState<any>([]);
	let [classifyItem, setClassifyItem] = useState<any>([]);
	let [allClassifyItem, setAllClassifyItem] = useState<any>([]);

	const getAreaList = async () => {
		const res = await areaList({
			cityCode: "410100",
			pageIndex: "1",
			pageSize: "99",
		});
		!isUnMounted &&
			setArea(
				getArray(res?.data.records).map((item) => ({
					label: item?.areaName,
					value: item?.areaCode,
				}))
			);
	};

	const getClassify = async () => {
		const res = await classifyList({
			classifyType: "400",
		});

		!isUnMounted && setAllClassifyItem(getArray(res?.data));

		// !isUnMounted &&
		// 	setClassifyItem(
		// 		getArray(res?.data[0]?.list).map((item) => ({
		// 			label: item?.classifyName,
		// 			value: item?.id,
		// 		}))
		// 	);
	};
	// 表格项
	const columns: ProColumns[] = [
		{
			title: "所属分类",
			dataIndex: "classifyId",
			hideInTable: true,
			renderFormItem: (
				item,
				{ type, defaultRender, record, ...rest },
				filterForm
			) => {
				return (
					<div>
						<Cascader
							options={allClassifyItem}
							fieldNames={{
								label: "classifyName",
								value: "id",
								children: "list",
							}}
							changeOnSelect
							onChange={async (value: any, selectedOptions: any) => {
								filterForm.setFieldsValue({
									classifyId: value,
								});
							}}
							placeholder="请选择类别~"
						/>
					</div>
				);
			},
		},
		{
			title: "推荐商品",
			dataIndex: "recommend",
			hideInTable: true,
			valueEnum: {
				1: "是",
				0: "否",
			},
		},
		{
			title: "关键词搜索",
			dataIndex: "goodsName",
			hideInTable: true,
		},
		// 查询项
		{
			title: "商品名称",
			dataIndex: "goodsName",
			search: false,
		},
		{
			title: "商品图片",
			dataIndex: "goodsIcon",
			search: false,
			render: (_, record: any) => {
				return (
					<Image.PreviewGroup>
						{record.goodsIcon.split(",").map((item: any) => {
							return (
								<Image
									style={{ marginLeft: "5" + "px" }}
									src={item}
									width={50}
									alt=""
								/>
							);
						})}
					</Image.PreviewGroup>
				);
			},
		},
		{
			title: "所属品类",
			dataIndex: "goodsClassifyName",
			search: false,
		},
		{
			title: "商品价格",
			dataIndex: "goodsPrice",
			search: false,
		},
		{
			title: "推荐位",
			dataIndex: "recommend",
			search: false,
			valueEnum: {
				1: "是",
				0: "否",
			},
		},

		{
			title: "添加日期",
			dataIndex: "createTime",
			search: false,
		},
		{
			title: "商品原价(元)",
			dataIndex: "goodsOriginPrice",
			search: false,
			render: (_, record: any) => {
				return record.goodsOriginPrice / 100;
			},
		},
		{
			title: "商品价格(元)",
			dataIndex: "goodsPrice",
			search: false,
			render: (_, record: any) => {
				return record.goodsPrice / 100;
			},
		},
		{
			title: "售出状态",
			dataIndex: "sellStatus",
			search: false,
			valueEnum: {
				10: "上架中",
				20: "已售出",
			},
		},
	];

	// 表单项
	const getFormItems = (vm: any, isEdit?: boolean): DynamicFormItem[] => {
		const { coupon } = vm.state;
		return [
			{
				type: "text",
				label: "商品名称",
				name: "goodsName",
				required: true,
			},
			{
				type: "upload",
				label: "商品图片",
				name: "goodsIcon",
				fieldProps: {
					limit: 6,
				},
				required: true,
			},
			{
				type: "upload",
				label: "视频讲解",
				name: "goodsVideo",
				fieldProps: {
					limit: 1,
				},
			},
			{
				type: "upload",
				label: "详情图片",
				name: "goodsDesc",
				fieldProps: {
					limit: 6,
				},
				required: true,
			},

			{
				type: "number",
				label: "商品价格",
				name: "goodsPrice",
				required: true,
			},
			{
				type: "select",
				label: "成色",
				name: "standard",
				required: true,
				options: conditionList,
			},
			{
				type: "number",
				label: "商品原价",
				name: "goodsOriginPrice",
				required: true,
			},
			{
				type: "select",
				label: "吊牌/包装",
				name: "packing",
				required: true,
				options: [
					{
						label: "有吊牌",
						value: "有吊牌",
					},
					{
						label: "有包装",
						value: "有包装",
					},
					{
						label: "无",
						value: "无",
					},
				],
			},
			{
				type: "text",
				label: "购入年份",
				name: "buyYear",
			},
			{
				type: "select",
				label: "配送区域",
				name: "areaCode",
				options: area,
				fieldProps: {
					mode: "multiple",
				},
			},
			{
				type: "custom",
				label: "所属分类",
				required: true,
				name: "classifyId",
				render: (form: any, record: any) => {
					return (
						<div>
							<Cascader
								defaultValue={[record.goodsClassifyName] || ""}
								options={allClassifyItem}
								fieldNames={{
									label: "classifyName",
									value: "id",
									children: "list",
								}}
								changeOnSelect
								onChange={(item) => {
									form.setFieldsValue({
										classifyId: item[item.length - 1],
									});
								}}
								placeholder="请选择类别~"
							/>
						</div>
					);
				},
			},
			{
				type: "custom",
				label: "推荐位",
				name: "recommend",
				required: true,
				render: (form: any, record: any) => {
					return (
						<Radio.Group
							options={recommendList}
							defaultValue={record.recommend}
							onChange={({ target }) => {
								form?.setFieldsValue({ recommend: target?.value });
								vm.setState({
									isTrue: target.value == 1,
								});
							}}
						></Radio.Group>
					);
				},
			},
			...(vm.state.isTrue == 1
				? [
						{
							type: "upload",
							label: "推荐位banner",
							name: "banner",
							fieldProps: {
								limit: 1,
							},
							required: true,
						},
				  ]
				: []),
			{
				type: "custom",
				label: "状态",
				name: "status",
				required: true,
				render: (form: any, record: any) => {
					return (
						<Radio.Group
							options={statusList}
							defaultValue={record.status}
							onChange={({ target }) => {
								form?.setFieldsValue({ status: target?.value });
							}}
						></Radio.Group>
					);
				},
			},
		];
	};

	// 一体化表格props
	const tablePorps: IntegrationTableProps = {
		rowKey: "goodsCode",
		scroll: { x: 1000 },
		columns,
		listProps: {
			url: "/goods/list",
			method: "GET",
			requestType: "params",
			paramsHandle: (params: any) => {
				return {
					...params,
					goodsType: 4,
				};
			},
		},
		addProps: {
			url: "/goods/add",
			modalProps: {
				width: 560,
				formProps: {
					labelCol: { span: 7 },
				},
				formItemsHandle: (_: any, vm: any) => {
					return getFormItems(vm);
				},
			},
			paramsHandle: ({ ...params }): any => {
				params.goodsIcon = (
					params?.goodsIcon?.map((item: any) => item.url) || []
				).join(",");

				params.goodsDesc = (
					params?.goodsDesc?.map((item: any) => item.url) || []
				).join(",");

				params.banner = (
					params?.banner?.map((item: any) => item.url) || []
				).join(",");

				params.goodsVideo = (
					params?.goodsVideo?.map((item: any) => item.url) || []
				).join(",");
				return {
					cityCode: "410100",
					...params,
					goodsPrice: (Number(params.goodsPrice) * 100).toFixed(0),
					goodsOriginPrice: (Number(params.goodsOriginPrice) * 100).toFixed(0),
					areaCode: getArray(params.areaCode).toString(),
					goodsType: 4,
				};
			},
		},
		updateProps: {
			url: "/goods/edit",
			method: "POST",
			btnText: (record: any) => {
				return record?.sellStatus == 20 ? "" : "编辑";
			},
			modalProps: {
				width: 560,
				formProps: {
					labelCol: { span: 7 },
				},
				formItemsHandle: (_: any, vm: any) => {
					return getFormItems(vm, true);
				},
				formValuesHandle: async (record: any) => {
					return {
						...record,
						goodsIcon: !!record.goodsIcon
							? [
									...record.goodsIcon
										.split(",")
										.map((item: any, index: any) => {
											return {
												uid: index,
												status: "done",
												name: item,
												url: item,
											};
										}),
							  ]
							: [],

						goodsDesc: !!record.goodsDesc
							? [
									...record.goodsDesc
										.split(",")
										.map((item: any, index: any) => {
											return {
												uid: index,
												status: "done",
												name: item,
												url: item,
											};
										}),
							  ]
							: [],

						goodsVideo: record?.goodsVideo
							? [
									{
										uid: "-1",
										status: "done",
										name: record.goodsVideo,
										url: record.goodsVideo,
									},
							  ]
							: [],

						banner: record?.banner
							? [
									{
										uid: "-1",
										status: "done",
										name: record.banner,
										url: record.banner,
									},
							  ]
							: [],

						goodsPrice: record.goodsPrice / 100,
						goodsOriginPrice: record.goodsOriginPrice / 100,
						areaCode: record.areaCode ? record?.areaCode?.split(",") : [],
					};
				},
				content: {
					onInit: async (vm) => {
						vm.setState({
							isTrue: vm.state?.record?.recommend,
						});
					},
				},
			},
			paramsHandle: ({ ...params }): any => {
				params.goodsIcon = (
					params?.goodsIcon?.map((item: any) => item.url) || []
				).join(",");
				params.goodsDesc = (
					params?.goodsDesc?.map((item: any) => item.url) || []
				).join(",");

				params.banner = (
					params?.banner?.map((item: any) => item.url) || []
				).join(",");

				params.goodsVideo = (
					params?.goodsVideo?.map((item: any) => item.url) || []
				).join(",");
				return {
					...params,
					areaCode: getArray(params.areaCode).toString(),
					goodsPrice: (Number(params.goodsPrice) * 100).toFixed(0),
					goodsOriginPrice: (Number(params.goodsOriginPrice) * 100).toFixed(0),
					goodsType: 4,
				};
			},
		},
		deleteProps: {
			url: "/goods/del",
			method: "POST",
			btnText: (record: any) => {
				return record?.sellStatus == 20 ? "" : "删除";
			},
		},
	};

	// 初始化加载数据
	useEffect(() => {
		getAreaList();
		getClassify();
		return () => {
			isUnMounted = true;
		};
	}, []);

	return <IntegrationTable {...tablePorps} />;
};

export default Business;
